<?php

class PsiController extends Controller {

    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array(
                    'Pricing', 'Create', 'Update', 'DelPricing', 'ProductPop',
                    'Product', 'CreateProduct', 'UpdateProduct', 'DelProduct', 'Vendor',
                    'CreateVendor', 'UpdateVendor', 'DelVendor', 'select', 'VendorPop',
                    'DynamicClass', 'ExportPricing', 'batchUpdate', 'CreateProductBatch', 'updateBox',
                    'tracking', 'TrackingUpdate', 'TrackingDelete', 'addTrackingItem', 'deleteTrackingItem',
                    'addMid', 'exportTracking'
                ),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function actionIndex() {
        $this->render('index');
    }

    public function actionPricing() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.PricingIndex desc';
        $criteria->with = 'product';
        $criteria->addCondition("t.BuySell='Buy'");
        $criteria->addCondition("t.Balance>0");

        $search['OrderName'] = $_REQUEST['OrderName'];
        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['Buyer'] = $_REQUEST['Buyer'];
        $search['ReceiptNo'] = $_REQUEST['ReceiptNo'];
        $search['ProductDetail'] = trim($_REQUEST['ProductDetail']);
        $search['ToLAMethod'] = $_REQUEST['ToLAMethod'];
        $search['Event'] = $_REQUEST['Event'];
        $search['Destination1'] = $_REQUEST['Destination1'];
        $search['Destination2'] = $_REQUEST['Destination2'];
        $search['sDate'] = $_REQUEST['sDate'];
        $search['eDate'] = $_REQUEST['eDate'];
        $search['sCreateTime'] = $_REQUEST['sCreateTime'];
        $search['eCreateTime'] = $_REQUEST['eCreateTime'];

        if ($search['OrderName']) {
            $criteria->addCondition("t.OrderName like '%" . $search['OrderName'] . "%'");
        }
        if ($search['ProductModel']) {
            $criteria->addCondition("[product].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['Buyer']) {
            $criteria->addCondition("t.Buyer='" . $search['Buyer'] . "'");
        }
        if ($search['ReceiptNo']) {
            $criteria->addCondition("t.ReceiptNo like '%" . $search['ReceiptNo'] . "%'");
        }

        if ($search['ProductDetail']) {
            $criteria->addCondition("[t].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['ToLAMethod']) {
            $criteria->addCondition("t.ToLAMethod='" . $search['ToLAMethod'] . "'");
        }
        if ($search['Event']) {
            $criteria->addCondition("t.Event='" . $search['Event'] . "'");
        }
        if ($search['Destination1']) {
            $criteria->addCondition("t.Destination1='" . $search['Destination1'] . "'");
        }
        if ($search['Destination2']) {
            $criteria->addCondition("t.Destination2='" . $search['Destination2'] . "'");
        }
        if ($search['sDate']) {
            $criteria->addCondition("t.Date>='" . $search['sDate'] . "'");
        }
        if ($search['eDate']) {
            $criteria->addCondition("t.Date<'" . $search['eDate'] . "'");
        }
        if ($search['sCreateTime']) {
            $criteria->addCondition("t.BoxNum>='" . $search['sCreateTime'] . "'");
        }
        if ($search['eCreateTime']) {
            $criteria->addCondition("t.BoxNum<'" . $search['eCreateTime'] . "'");
        }

        $labels = Pricing::model()->attributeLabels();

        $count = Pricing::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Pricing::model()->findAll($criteria);
        $this->render('pricing', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }

    //导出Pricing
    public function actionExportPricing() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.PricingIndex desc';
        $criteria->with = 'product';
        $criteria->addCondition("t.BuySell='Buy'");
        $criteria->addCondition("t.Balance>0");

        $search['OrderName'] = $_REQUEST['OrderName'];
        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['Buyer'] = $_REQUEST['Buyer'];
        $search['ReceiptNo'] = $_REQUEST['ReceiptNo'];
        $search['ProductName'] = $_REQUEST['ProductName'];
        $search['ToLAMethod'] = $_REQUEST['ToLAMethod'];
        $search['Event'] = $_REQUEST['Event'];
        $search['Destination1'] = $_REQUEST['Destination1'];
        $search['Destination2'] = $_REQUEST['Destination2'];
        $search['Date'] = $_REQUEST['Date'];

        if ($search['OrderName']) {
            $criteria->addCondition("t.OrderName like '%" . $search['OrderName'] . "%'");
        }
        if ($search['ProductModel']) {
            $criteria->addCondition("[product].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['Buyer']) {
            $criteria->addCondition("t.Buyer='" . $search['Buyer'] . "'");
        }
        if ($search['ReceiptNo']) {
            $criteria->addCondition("t.ReceiptNo like '%" . $search['ReceiptNo'] . "%'");
        }

        if ($search['ProductName']) {
            $criteria->addCondition("[product].[ProductName] like '%" . $search['ProductName'] . "%'");
        }
        if ($search['ToLAMethod']) {
            $criteria->addCondition("t.ToLAMethod='" . $search['ToLAMethod'] . "'");
        }
        if ($search['Event']) {
            $criteria->addCondition("t.Event='" . $search['Event'] . "'");
        }
        if ($search['Destination1']) {
            $criteria->addCondition("t.Destination1='" . $search['Destination1'] . "'");
        }
        if ($search['Destination2']) {
            $criteria->addCondition("t.Destination2='" . $search['Destination2'] . "'");
        }
        if ($search['Date']) {
            $criteria->addCondition("t.Date='" . $search['Date'] . "'");
        }

        $rowTable = Pricing::model()->findAll($criteria);
        
        $pricings = array();
        foreach($rowTable as $row){
            if($row->mids){
                foreach ($row->mids as $mid) {
                    $data = array(
                        'ProductModel' => $row->ProductModel,
                        'ProductDetail' => $row->ProductDetail,
                        'InspectWay' => $row->InspectWay,
                        'TakePictures' => $row->TakePictures,
                        'PQuantity' => $row->PQuantity,
                        'Balance' => $row->Balance,
                        'ToLAQty' => $mid->ToLAQty,                        
                        'CarrierNo' => $mid->tracking->CarrierNo,
                        'Event' => $row->Event,
                        'Inspector' => $row->Inspector,
                        'ToLAMethod' => $row->ToLAMethod,
                        'ProductLink' => $row->ProductLink,
                        'OEFeedback' => $row->OEFeedback,
                    );
                    if($data->tracking->ShippingType=='Container'){
                        $data['BoxNumber'] = $mid->CBoxNumber;
                    }else{
                        $data['BoxNumber'] = $mid->tracking->EBoxNumber;
                    }
                    $pricings[] = $data;
                    unset($data);
                }
            }else{
                $pricings[] = array(
                    'ProductModel' => $row->ProductModel,
                    'ProductDetail' => $row->ProductDetail,
                    'InspectWay' => $row->InspectWay,
                    'TakePictures' => $row->TakePictures,
                    'PQuantity' => $row->PQuantity,
                    'Balance' => $row->Balance,
                    'ToLAQty' => '',
                    'BoxNumber' => '',
                    'CarrierNo' => '',
                    'Event' => $row->Event,
                    'Inspector' => $row->Inspector,
                    'ToLAMethod' => $row->ToLAMethod,
                    'ProductLink' => $row->ProductLink,
                    'OEFeedback' => $row->OEFeedback,
                );
            }
        }

        spl_autoload_unregister(array('YiiBase', 'autoload'));
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel.php');
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel/IOFactory.php');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '产品编号')
                ->setCellValue('B1', '产品细节')
                ->setCellValue('C1', '验货方式')
                ->setCellValue('D1', '是否拍照')
                ->setCellValue('E1', '购买数量')
                ->setCellValue('F1', '未处理数量')
                ->setCellValue('G1', '运出数量')                
                ->setCellValue('H1', '箱号')
                ->setCellValue('I1', '货柜编号')
                ->setCellValue('J1', '验货状态')
                ->setCellValue('K1', '验货人')
                ->setCellValue('L1', '运输方式')
                ->setCellValue('M1', '产品连接')
                ->setCellValue('N1', '验货反馈');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(50);

        $i = 2;
        foreach ($pricings as $item) {
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $i, $item['ProductModel'])
                    ->setCellValue('B' . $i, $item['ProductDetail'])
                    ->setCellValue('C' . $i, $item['InspectWay'])
                    ->setCellValue('D' . $i, $item['TakePictures'])
                    ->setCellValue('E' . $i, $item['PQuantity'])
                    ->setCellValue('F' . $i, $item['Balance'])
                    ->setCellValue('G' . $i, $item['ToLAQty'])
                    ->setCellValue('H' . $i, $item['BoxNumber'])
                    ->setCellValueExplicit('I' . $i, $item['CarrierNo'], PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('J' . $i, $item['Event'])
                    ->setCellValue('K' . $i, $item['Inspector'])
                    ->setCellValue('L' . $i, $item['ToLAMethod'])
                    ->setCellValue('M' . $i, $item['ProductLink'])
                    ->setCellValue('N' . $i, $item['OEFeedback']);
            $i++;
        }
        
        $filename = 'Pricing.xls';
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename=' . urlencode($filename) . '');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        spl_autoload_register(array('YiiBase', 'autoload'));
    }

    //新建Pricing
    public function actionCreate() {
        $model = new Pricing;
        if ($_GET['pid']) {
            $product = Product::model()->findByPk($_GET['pid']);
        }

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Pricing'])) {
            $model->attributes = $_POST['Pricing'];
            $model->Type = 'Product fee';
            $model->BuySell = 'Buy';
            $model->Mode = 'Order';
            $model->Label = 'Purchased';
            $model->PS = 'China';
            
            $model->Balance = $model->PQuantity;

            if ($model->save()) {
                
                if ($model->product) {
                    if ($_POST['ProdPackL_cm']) {
                        $model->product->ProdPackL_cm = (int)$_POST['ProdPackL_cm'];
                    }
                    if ($_POST['ProdPackW_cm']) {
                        $model->product->ProdPackW_cm = (int)$_POST['ProdPackW_cm'];
                    }
                    if ($_POST['ProdPackH_cm']) {
                        $model->product->ProdPackH_cm = (int)$_POST['ProdPackH_cm'];
                    }
                    if ($_POST['WeightG']) {
                        $model->product->WeightG = $_POST['WeightG'];
                    }
                    if ($_POST['BoxSizeL_cm']) {
                        $model->product->BoxSizeL_cm = (int)$_POST['BoxSizeL_cm'];
                    }
                    if ($_POST['BoxSizeW_cm']) {
                        $model->product->BoxSizeW_cm = (int)$_POST['BoxSizeW_cm'];
                    }
                    if ($_POST['BoxSizeH_cm']) {
                        $model->product->BoxSizeH_cm = (int)$_POST['BoxSizeH_cm'];
                    }
                    if ($_POST['WeighttoCust']) {
                        $model->product->WeighttoCust = $_POST['WeighttoCust'];
                    }
                    if ($_POST['BoxQuantity']) {
                        $model->product->BoxQuantity = (int)$_POST['BoxQuantity'];
                    }
                    if ($_POST['ProductSize']) {
                        $model->product->ProductSize = $_POST['ProductSize'];
                    }
                    $model->product->save();
                }
                
                $this->redirect(array('pricing'));
            }
        }

        if (!$model->OrderName) {
            $model->OrderName = Helper::getOrderNumber();
        }

        $this->render('create', array(
            'model' => $model,
            'product' => $product,
        ));
    }

    public function actionProductPop() {
        $this->layout = 'pop';

        $criteria = new CDbCriteria();
        $criteria->order = 't.ProductID desc';
        $criteria->addCondition("Type='MX'");

        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['ProductName'] = $_REQUEST['ProductName'];
        $search['ProductDetail'] = $_REQUEST['ProductDetail'];

        if ($search['ProductModel']) {
            $criteria->addCondition("[t].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['ProductName']) {
            $criteria->addCondition("[t].[ProductName] like '%" . $search['ProductName'] . "%'");
        }
        if ($search['ProductDetail']) {
            $criteria->addCondition("[t].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }

        $labels = Product::model()->attributeLabels();

        $count = Product::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Product::model()->findAll($criteria);
        $this->render('productpop', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }

    //更新Pricing
    public function actionUpdate($id) {        
        Helper::updateTrackingCacheByPricingIndex($id);
        $model = Pricing::model()->findByPk($id);
        $oldContent = $model->OEFeedback;
        $oldQty = $model->PQuantity;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Pricing'])) {
            $model->attributes = $_POST['Pricing'];
            if($model->PQuantity!=$oldQty){
                $model->Balance += $model->PQuantity-$oldQty;
                if($model->Balance<0){
                    header("Content-Type:text/html;charset=utf-8");
                    echo '<script>alert("订购数量出错，请检查！");window.location.href="' . Yii::app()->createUrl('psi/update',array('id'=>$id)) . '";</script>';
                    exit;
                }
            }
            if ($model->save()) {
                if ($model->OEFeedback != $oldContent) {
                    Helper::addFeedback($model->OEFeedback, $model->PricingIndex);
                }
                if ($model->product) {
                    if ($_POST['ProdPackL_cm']) {
                        $model->product->ProdPackL_cm = (int)$_POST['ProdPackL_cm'];
                    }
                    if ($_POST['ProdPackW_cm']) {
                        $model->product->ProdPackW_cm = (int)$_POST['ProdPackW_cm'];
                    }
                    if ($_POST['ProdPackH_cm']) {
                        $model->product->ProdPackH_cm = (int)$_POST['ProdPackH_cm'];
                    }
                    if ($_POST['WeightG']) {
                        $model->product->WeightG = $_POST['WeightG'];
                    }
                    if ($_POST['BoxSizeL_cm']) {
                        $model->product->BoxSizeL_cm = (int)$_POST['BoxSizeL_cm'];
                    }
                    if ($_POST['BoxSizeW_cm']) {
                        $model->product->BoxSizeW_cm = (int)$_POST['BoxSizeW_cm'];
                    }
                    if ($_POST['BoxSizeH_cm']) {
                        $model->product->BoxSizeH_cm = (int)$_POST['BoxSizeH_cm'];
                    }
                    if ($_POST['WeighttoCust']) {
                        $model->product->WeighttoCust = $_POST['WeighttoCust'];
                    }
                    if ($_POST['BoxQuantity']) {
                        $model->product->BoxQuantity = (int)$_POST['BoxQuantity'];
                    }
                    if ($_POST['ProductSize']) {
                        $model->product->ProductSize = $_POST['ProductSize'];
                    }
                    $model->product->save();
                }
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");window.open("","_parent","");window.close();</script>';
                exit;
                $this->redirect(array('pricing'));
            }
        }

        if (substr($model->Buyer, 0, 1) == 'A') {
            $form = '_form';
        } else {
            $form = '_form2';
        }

        $this->render('update', array(
            'model' => $model,
            'form' => $form,
        ));
    }

    //nr删除pricing，删除到另外一个备用表中，注明操作人和删除时间，只允许删除nr自己添加的记录
    public function actionDelPricing() {
        $pid = $_REQUEST['pid'];
        $pricing = Pricing::model()->findByPk($pid);
        if ($pricing) {
            $pricingD = new PricingDel;
            $pricingD->attributes = $pricing->attributes;
            if ($pricingD->save()) {
                $pricing->delete();
            }
        }
        echo CJSON::encode(array('success' => true, 'msg' => '删除成功!'));
    }

    //product列表
    public function actionProduct() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.ProductID desc';
        $criteria->addCondition("t.Type='MX'");

        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['ProductDetail'] = $_REQUEST['ProductDetail'];
        $search['Color'] = $_REQUEST['Color'];
        $search['Style'] = $_REQUEST['Style'];

        if ($search['ProductModel']) {
            $criteria->addCondition("[t].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['ProductDetail']) {
            $criteria->addCondition("[t].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['Color']) {
            $criteria->addCondition("[t].[Color] like '%" . $search['Color'] . "%'");
        }
        if ($search['Style']) {
            $criteria->addCondition("[t].[Style] like '%" . $search['Style'] . "%'");
        }

        $labels = Product::model()->attributeLabels();

        $count = Product::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Product::model()->findAll($criteria);
        $this->render('product', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }

    //新建Product
    public function actionCreateProduct() {
        $model = new Product;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];

            if ($model->save()) {
                $this->redirect(array('select', 'pid' => $model->ProductID));
            }
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='Category'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['classes'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->Category) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->Category . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['subclasses'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($subclasses);
            unset($condition);
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='OF1'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['OF1'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->OF1) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->OF1 . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['OF2'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($condition);
            unset($subclasses);
        }

        $this->render('createProduct', array(
            'model' => $model,
            'data' => $data,
        ));
    }

    //批量添加产品
    public function actionCreateProductBatch() {
        $data['num'] = $_REQUEST['num'] ? (int) $_REQUEST['num'] : 10;

        if (isset($_POST['Category'])) {
            $model = new Product;
            $model->Category = $_POST['Category'];
            $model->SubCategory = $_POST['SubCategory'];
            $model->OF1 = $_POST['OF1'];
            $model->OF2 = $_POST['OF2'];
            $model->VendorCode = $_POST['VendorCode'];

            $nidNo = Helper::getNIDNo();
            $model->NIDNo = $nidNo;

            $j = 0;
            $k = 0;

            for ($i = 1; $i <= $data['num']; $i++) {
                $productDetail = $_POST['ProductDetail_' . $i];
                if (!$productDetail) {//没有填写产品细节，这条记录就算没有添加
                    continue;
                }
                $k++;
                $product = new Product;
                $product->attributes = $model->attributes;
                $product->ProductDetail = $productDetail;
                $product->Color = $_POST['Color_' . $i];
                $product->Style = $_POST['Style_' . $i];
                $product->WeightG = $_POST['WeightG_' . $i];
                $product->ProdPackL_cm = $_POST['ProdPackL_cm_' . $i];
                $product->ProdPackW_cm = $_POST['ProdPackW_cm_' . $i];
                $product->ProdPackH_cm = $_POST['ProdPackH_cm_' . $i];

                if ($product->save()) {
                    $j++;
                }
                unset($product);
                unset($productDetail);
            }
            header("Content-Type:text/html;charset=utf-8");
            if ($j) {
                echo '<script>alert("批量添加成功");window.location.href="' . Yii::app()->createUrl('psi/product') . '";</script>';
            } elseif ($k) {
                echo '<script>alert("批量添加失败");</script>';
            } else {
                echo '<script>alert("请填入产品细节");</script>';
            }
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='Category'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['classes'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->Category) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->Category . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['subclasses'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($subclasses);
            unset($condition);
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='OF1'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['OF1'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->OF1) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->OF1 . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['OF2'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($condition);
            unset($subclasses);
        }

        $labels = Product::model()->attributeLabels();

        $this->render('productBatch', array(
            'model' => $model,
            'data' => $data,
            'labels' => $labels,
        ));
    }

    //更新Product
    public function actionUpdateProduct($id) {
        $model = Product::model()->findByPk($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            if ($model->save()) {
                $this->redirect(array('product'));
            }
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='Category'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['classes'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->Category) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->Category . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['subclasses'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($subclasses);
            unset($condition);
        }

        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='OF1'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['OF1'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->OF1) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->OF1 . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['OF2'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($condition);
            unset($subclasses);
        }

        $this->render('updateProduct', array(
            'model' => $model,
            'data' => $data,
        ));
    }

    //nr删除pricing，删除到另外一个备用表中，注明操作人和删除时间，只允许删除nr自己添加的记录
    public function actionDelProduct() {
        $pid = $_REQUEST['pid'];
        $product = Product::model()->findByPk($pid);
        if ($product) {
            $productD = new ProductDel;
            $productD->attributes = $product->attributes;
            if ($productD->save()) {
                $product->delete();
            }
        }
        echo CJSON::encode(array('success' => true, 'msg' => '删除成功!'));
    }

    //vendor列表
    public function actionVendor() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.ID desc';

        $search['CompanyName'] = $_REQUEST['CompanyName'];
        $search['Contact'] = $_REQUEST['Contact'];
        $search['Address'] = $_REQUEST['Address'];
        $search['CompanyPhone'] = $_REQUEST['CompanyPhone'];
        $search['ZipCode'] = $_REQUEST['ZipCode'];
        $search['City'] = $_REQUEST['City'];
        $search['QQNumber'] = $_REQUEST['QQNumber'];
        $search['WWNumber'] = $_REQUEST['WWNumber'];

        if ($search['CompanyName']) {
            $criteria->addCondition("[t].[CompanyName] like '%" . $search['CompanyName'] . "%'");
        }
        if ($search['Contact']) {
            $criteria->addCondition("[t].[Contact] like '%" . $search['Contact'] . "%'");
        }
        if ($search['Address']) {
            $criteria->addCondition("[t].[Address] like '%" . $search['Address'] . "%'");
        }
        if ($search['CompanyPhone']) {
            $criteria->addCondition("[t].[CompanyPhone] like '%" . $search['CompanyPhone'] . "%'");
        }
        if ($search['ZipCode']) {
            $criteria->addCondition("[t].[ZipCode] like '%" . $search['ZipCode'] . "%'");
        }
        if ($search['City']) {
            $criteria->addCondition("[t].[City] like '%" . $search['City'] . "%'");
        }
        if ($search['QQNumber']) {
            $criteria->addCondition("[t].[QQNumber] like '%" . $search['QQNumber'] . "%'");
        }
        if ($search['WWNumber']) {
            $criteria->addCondition("[t].[WWNumber] like '%" . $search['WWNumber'] . "%'");
        }

        $labels = Vendor::model()->attributeLabels();

        $count = Vendor::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Vendor::model()->findAll($criteria);
        $this->render('vendor', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }

    //新建Product
    public function actionCreateVendor() {
        $model = new Vendor();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Vendor'])) {
            $model->attributes = $_POST['Vendor'];

            if ($model->save()) {
                $this->redirect(array('vendor'));
            }
        }

        $this->render('createVendor', array(
            'model' => $model,
        ));
    }

    //更新Product
    public function actionUpdateVendor($id) {
        $model = Vendor::model()->findByPk($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Vendor'])) {
            $model->attributes = $_POST['Vendor'];
            if ($model->save()) {
                $this->redirect(array('vendor'));
            }
        }

        $this->render('updateVendor', array(
            'model' => $model,
        ));
    }

    //nr删除pricing，删除到另外一个备用表中，注明操作人和删除时间，只允许删除nr自己添加的记录
    public function actionDelVendor() {
        $pid = $_REQUEST['pid'];
        $product = Vendor::model()->findByPk($pid);
        if ($product) {
            $productD = new VendorDel;
            $productD->attributes = $product->attributes;
            if ($productD->save()) {
                $product->delete();
            }
        }
        echo CJSON::encode(array('success' => true, 'msg' => '删除成功!'));
    }

    //添加产品后选择页面
    public function actionSelect($pid) {
        $this->render('select', array(
            'pid' => $pid,
        ));
    }

    public function actionVendorPop() {
        $this->layout = 'pop';

        $criteria = new CDbCriteria();
        $criteria->order = 't.ID desc';

        $search['CompanyName'] = $_REQUEST['CompanyName'];
        $search['Contact'] = $_REQUEST['Contact'];
        $search['Address'] = $_REQUEST['Address'];
        $search['CompanyPhone'] = $_REQUEST['CompanyPhone'];
        $search['ZipCode'] = $_REQUEST['ZipCode'];
        $search['City'] = $_REQUEST['City'];
        $search['QQNumber'] = $_REQUEST['QQNumber'];
        $search['WWNumber'] = $_REQUEST['WWNumber'];

        if ($search['CompanyName']) {
            $criteria->addCondition("[t].[CompanyName] like '%" . $search['CompanyName'] . "%'");
        }
        if ($search['Contact']) {
            $criteria->addCondition("[t].[Contact] like '%" . $search['Contact'] . "%'");
        }
        if ($search['Address']) {
            $criteria->addCondition("[t].[Address] like '%" . $search['Address'] . "%'");
        }
        if ($search['CompanyPhone']) {
            $criteria->addCondition("[t].[CompanyPhone] like '%" . $search['CompanyPhone'] . "%'");
        }
        if ($search['ZipCode']) {
            $criteria->addCondition("[t].[ZipCode] like '%" . $search['ZipCode'] . "%'");
        }
        if ($search['City']) {
            $criteria->addCondition("[t].[City] like '%" . $search['City'] . "%'");
        }
        if ($search['QQNumber']) {
            $criteria->addCondition("[t].[QQNumber] like '%" . $search['QQNumber'] . "%'");
        }
        if ($search['WWNumber']) {
            $criteria->addCondition("[t].[WWNumber] like '%" . $search['WWNumber'] . "%'");
        }

        $labels = Vendor::model()->attributeLabels();

        $count = Vendor::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Vendor::model()->findAll($criteria);
        $this->render('vendorpop', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }

    public function actionDynamicClass($class) {
        if ($class) {
            $data = FieldOption::model()->findAll("Bridge='" . $class . "'");
            $data = CHtml::listData($data, 'Field_Options', 'Field_Options');
            if ($data) {
                echo CHtml::tag('option', array('value' => ''), CHtml::encode('请选择'), true);
                foreach ($data as $value => $name) {
                    echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
                }
            } else {
                echo CHtml::tag('option', array('value' => 0), CHtml::encode('请选择'), true);
            }
        } else {
            echo CHtml::tag('option', array('value' => 0), CHtml::encode('请选择'), true);
        }
    }

    //Pricing验货批量更新
    public function actionBatchUpdate() {
        $this->layout = 'pop';

        if (isset($_POST['PricingIndex']) && $_POST['PricingIndex']) {
            $receiptNo = $_POST['ReceiptNo'];
            $pricingIndexArr = $_POST['PricingIndex'];
            $inspector = $_POST['Inspector'];
            $inspectDate = $_POST['InspectDate'];
            $event = $_POST['Event'];

            $conditon = new CDbCriteria();
            $conditon->addInCondition('PricingIndex', $pricingIndexArr);
            $conditon->addCondition("ReceiptNo='" . $receiptNo . "'");
            $rowTable = Pricing::model()->findAll($conditon);
            unset($conditon);
            if ($rowTable) {
                foreach ($rowTable as $row) {
                    if ($inspector) {
                        $row->Inspector = $inspector;
                    }
                    if ($inspectDate) {
                        $row->InspectDate = $inspectDate;
                    }
                    if ($event) {
                        $row->Event = $event;
                    }
                    
                    if ($row->OEFeedback != $_POST['OEFeedback_' . $row->PricingIndex]) {
                        $row->OEFeedback = $_POST['OEFeedback_' . $row->PricingIndex];
                        Helper::addFeedback($row->OEFeedback, $row->PricingIndex);                        
                    }
                    $row->save();
                    if ($row->product) {
                        if ($_POST['ProdPackL_cm_' . $row->PricingIndex]) {
                            $row->product->ProdPackL_cm = $_POST['ProdPackL_cm_' . $row->PricingIndex];
                            $row->product->save();
                        }
                        if ($_POST['ProdPackW_cm_' . $row->PricingIndex]) {
                            $row->product->ProdPackW_cm = $_POST['ProdPackW_cm_' . $row->PricingIndex];
                            $row->product->save();
                        }
                        if ($_POST['ProdPackH_cm_' . $row->PricingIndex]) {
                            $row->product->ProdPackH_cm = $_POST['ProdPackH_cm_' . $row->PricingIndex];
                            $row->product->save();
                        }
                        if ($_POST['WeightG_' . $row->PricingIndex]) {
                            $row->product->WeightG = $_POST['WeightG_' . $row->PricingIndex];
                            $row->product->save();
                        }
                    }
                }
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");parent.$.fancybox.close();</script>';
            }
        }

        $receiptNo = $_GET['ReceiptNo'];
        if ($receiptNo) {
            $rowTable = Pricing::model()->findAll("ReceiptNo='" . $receiptNo . "'");
        }

        $labels = Pricing::model()->attributeLabels();
        $this->render('batchpop', array(
            'rowTable' => $rowTable,
            'labels' => $labels,
            'receiptNo' => $receiptNo,
        ));
    }

    //更新箱号
    public function actionUpdateBox() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.PricingIndex desc';
        $criteria->with = 'product';
        $criteria->addCondition("t.Destination1='BP'");
        $criteria->addCondition("t.Event='P'");
        $criteria->addCondition("t.CarrierNumber='' or t.CarrierNumber is null");
        $criteria->addCondition("t.BoxNum='' or t.BoxNum is null");

        $search['InspectDate'] = $_REQUEST['InspectDate'];
        $search['ProductDetail'] = $_REQUEST['ProductDetail'];

        if ($search['ProductDetail']) {
            $criteria->addCondition("[product].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['InspectDate']) {
            $criteria->addCondition("t.InspectDate='" . $search['InspectDate'] . "'");
        }

        $labels = Pricing::model()->attributeLabels();

        $rowTable = Pricing::model()->findAll($criteria);

        if (isset($_POST['boxBatch'])) {
            $receiptNo = $_POST['ReceiptNo'];
            $pricingIndexArr = $_POST['PricingIndex'];
            $inspector = $_POST['Inspector'];
            $inspectDate = $_POST['InspectDate'];
            $event = $_POST['Event'];
            $toLAMethod = $_POST['ToLAMethod'];
            $carrierNumber = $_POST['CarrierNumber'];

            if ($rowTable) {
                foreach ($rowTable as $row) {
                    $row->ToLAQty = $_POST['ToLAQty_' . $row->PricingIndex];
                    $row->BoxNum = $_POST['BoxNum_' . $row->PricingIndex];
                    $row->CarrierNumber = $_POST['CarrierNumber_' . $row->PricingIndex];
                    if ($row->ToLAQty && $row->BoxNum && $row->CarrierNumber) {
                        $row->save();
                    }
                }
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");window.location.href="' . Yii::app()->createUrl('psi/updateBox') . '";</script>';
            }
        }

        $this->render('updateBox', array('rowTable' => $rowTable, 'search' => $search, 'labels' => $labels));
    }

    //tracking管理
    public function actionTracking() {
        $this->layout = 'column2';
        if ($_POST['TrackingIndexs']) {
            foreach ($_POST['TrackingIndexs'] as $index) {
                $tracking = Tracking::model()->findByPk((int) $index);
                if ($tracking) {
                    $tracking->OETrackingStatus = $_POST['OETrackingStatus_' . $index];
                    $tracking->save();
                }
            }
            $alertMsg = '更新成功';
        }

        $criteria = new CDbCriteria();
        $criteria->order = 'EBoxNumber desc,TrackingIndex desc';

        $search['ShippingStatus'] = $_REQUEST['ShippingStatus'];
        $search['CarrierNo'] = $_REQUEST['CarrierNo'];
        $search['EBoxNumber'] = $_REQUEST['EBoxNumber'];
        $search['ToLAMethod'] = $_REQUEST['ToLAMethod'];
        $search['ShipDate'] = $_REQUEST['ShipDate'];
        $search['ArriveDate'] = $_REQUEST['ArriveDate'];
        $search['ShippingType'] = $_REQUEST['ShippingType'];

        if ($search['ShippingStatus']) {
            $criteria->addCondition("ShippingStatus='" . $search['ShippingStatus'] . "'");
        }
        if ($search['CarrierNo']) {
            $criteria->addCondition("t.CarrierNo like '%" . $search['CarrierNo'] . "%'");
        }
        if ($search['EBoxNumber']) {
            $criteria->addCondition("t.EBoxNumber like '%" . $search['EBoxNumber'] . "%'");
        }
        if ($search['ToLAMethod']) {
            $criteria->addCondition("t.ToLAMethod = '" . $search['ToLAMethod'] . "'");
        }
        if ($search['ShipDate']) {
            $criteria->addCondition("t.ShipDate='" . $search['ShipDate'] . "'");
        }
        if ($search['ArriveDate']) {
            $criteria->addCondition("t.ArriveDate='" . $search['ArriveDate'] . "'");
        }
        if ($search['ShippingType']) {
            $criteria->addCondition("t.ShippingType='" . $search['ShippingType'] . "'");
        }

        $labels = Tracking::model()->attributeLabels();

        $count = Tracking::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Tracking::model()->findAll($criteria);
        $this->render('tracking', array(
            'rowTable' => $rowTable,
            'search' => $search,
            'pages' => $pager,
            'labels' => $labels,
            'alertMsg' => $alertMsg,
        ));
    }

    //Tracking详情
    public function actionTrackingUpdate() {
        $this->layout = 'column2';
        $trackingIndex = $_REQUEST['trackingIndex'];
        if ($trackingIndex) {
            $model = Tracking::model()->findByPk((int) $trackingIndex);
        }

        if (!$model) {
            $model = new Tracking;
            $model->ShippingStatus = 'DataLogging';
        }

        if (isset($_POST['Tracking'])) {
            if ($model->ShippingStatus == 'DataLogging') {
                $model->attributes = $_POST['Tracking'];
                $new = $model->isNewRecord;
                if ($model->save()) {
                    //更新midtab记录
                    if ($model->mids) {
                        foreach ($model->mids as $mid) {
                            $mid->ToLAQty = trim($_POST['ToLAQty_' . $mid->MidIndex]);
                            $mid->CBoxNumber = trim($_POST['BoxNum_' . $mid->MidIndex]);
                            $mid->save();
                        }
                    }
                    if ($new) {
                        $msg = '创建成功';
                    } else {
                        $msg = '更新成功';
                    }
                }
            } else {
                $model->ArriveDate = $_POST['Tracking']['ArriveDate'];
                $model->Comment = $_POST['Tracking']['Comment'];
                $model->OETrackingStatus = $_POST['Tracking']['OETrackingStatus'];
                if ($model->save()) {
                    $msg = '更新成功';
                }
            }
            if ($msg) {
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("' . $msg . '");window.location.href="' . Yii::app()->createUrl('psi/TrackingUpdate', array('trackingIndex' => $model->TrackingIndex)) . '";</script>';
            }
        }
        if ($model->ShipDate) {
            $model->ShipDate = date('Ymd', strtotime($model->ShipDate));
        }
        if ($model->ArriveDate) {
            $model->ArriveDate = date('Ymd', strtotime($model->ArriveDate));
        }
        
        if($model->mids){
            foreach($model->mids as $item){
                Helper::updateTrackingCacheByPricingIndex($item->PricingIndex);
            }
        }

        $this->render('trackingDetail', array(
            'model' => $model,
        ));
    }

    //删除Tracking
    public function actionTrackingDelete() {
        $TrackingIndex = $_REQUEST['TrackingIndex'];
        $model = Tracking::model()->findByPk((int) $TrackingIndex);
        if ($model && $model->ShippingStatus == 'DataLogging') {
            if ($model->delete()) {
                $msg = '删除成功';
            } else {
                $msg = '删除失败';
            }
        } else {
            $msg = '运输状态为”'.$model->ShippingStatus.'”，记录不能删除，请联系管理员解决';
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }

    //关联pricing
    public function actionAddTrackingItem($trackingIndex) {
        $this->layout = 'pop';

        $tracking = Tracking::model()->findByPk($trackingIndex);
        if ($tracking->ShippingStatus == 'Delivery') {
            header("Content-Type:text/html;charset=utf-8");
            echo '<script>alert("不允许更新");parent.$.fancybox.close();</script>';
        }

        if ($_POST['PricingIndexs']) {
            $msg = '';
            foreach ($_POST['PricingIndexs'] as $pricingIndex) {
                $condition = new CDbCriteria();
                $condition->addCondition('TrackingIndex=' . $trackingIndex);
                $condition->addCondition('PricingIndex=' . $pricingIndex);
                $have = MidTab::model()->find($condition);
                unset($condition);
                if (!$have) {
                    $pricing = Pricing::model()->findByPk((int) $pricingIndex);
                    $model = new MidTab();
                    $model->TrackingIndex = $trackingIndex;
                    $model->PricingIndex = $pricingIndex;
                    $model->ProductID = $pricing->ProductID;
                    $model->ToLAQty = (int) trim($_POST['ToLAQty_' . $pricingIndex]);
                    $model->CBoxNumber = trim($_POST['BoxNum_' . $pricingIndex]);
                    $model->save();
                }
            }
            header("Content-Type:text/html;charset=utf-8");
            echo '<script>alert("关联成功");</script>';
        }

        $tracking = Tracking::model()->findByPk($trackingIndex);

        $criteria = new CDbCriteria();
        $criteria->order = 't.PricingIndex desc';
        $criteria->with = 'product';
        $criteria->addCondition("t.BuySell='Buy'");
        $criteria->addCondition("t.Balance>0");
        $criteria->addCondition("t.Balance-t.ToLAQty>0");
        $criteria->addCondition("t.Event='P'");
//        if($tracking->ShippingType=='Express'){
//            $criteria->addCondition("t.Destination1='OE'");
//        }else{
//            $criteria->addCondition("t.Destination1='BP'");
//        }
        $criteria->addNotInCondition('t.PricingIndex', CHtml::listData($tracking->mids, 'PricingIndex', 'PricingIndex'));


        $search['OrderName'] = $_REQUEST['OrderName'];
        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['Buyer'] = $_REQUEST['Buyer'];
        $search['ReceiptNo'] = $_REQUEST['ReceiptNo'];
        $search['ProductDetail'] = trim($_REQUEST['ProductDetail']);
        $search['ToLAMethod'] = $_REQUEST['ToLAMethod'];
        $search['Event'] = $_REQUEST['Event'];
        $search['Destination1'] = $_REQUEST['Destination1'];
        $search['Destination2'] = $_REQUEST['Destination2'];
        $search['Date'] = $_REQUEST['Date'];

        if ($search['OrderName']) {
            $criteria->addCondition("t.OrderName like '%" . $search['OrderName'] . "%'");
        }
        if ($search['ProductModel']) {
            $criteria->addCondition("[product].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['Buyer']) {
            $criteria->addCondition("t.Buyer='" . $search['Buyer'] . "'");
        }
        if ($search['ReceiptNo']) {
            $criteria->addCondition("t.ReceiptNo like '%" . $search['ReceiptNo'] . "%'");
        }

        if ($search['ProductDetail']) {
            $criteria->addCondition("[t].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['ToLAMethod']) {
            $criteria->addCondition("t.ToLAMethod='" . $search['ToLAMethod'] . "'");
        }
        if ($search['Event']) {
            $criteria->addCondition("t.Event='" . $search['Event'] . "'");
        }
        if ($search['Destination1']) {
            $criteria->addCondition("t.Destination1='" . $search['Destination1'] . "'");
        }
        if ($search['Destination2']) {
            $criteria->addCondition("t.Destination2='" . $search['Destination2'] . "'");
        }
        if ($search['Date']) {
            $criteria->addCondition("t.Date='" . $search['Date'] . "'");
        }

        $labels = Pricing::model()->attributeLabels();

        $count = Pricing::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Pricing::model()->findAll($criteria);

        //更新pricing ToLAQty
        foreach ($rowTable as $row) {
            Helper::updateTrackingCacheByPricingIndex($row->PricingIndex);
        }

        $this->render('pricingpop', array(
            'rowTable' => $rowTable,
            'search' => $search,
            'pages' => $pager,
            'labels' => $labels,
            'model' => $tracking,
        ));
    }

    //删除TrackingItem
    public function actionDeleteTrackingItem($id, $pid = '') {
        $model = MidTab::model()->findByPk((int) $id);
        
        if ($model && $model->tracking->ShippingStatus == 'DataLogging') {
            $tid = $model->TrackingIndex;
            $model->delete();
            $msg = '删除成功';
        } else {
            $msg = '运输状态为”'.$model->ShippingStatus.'”，记录不能删除，请联系管理员解决';
        }
        
        if (!$pid) {
            $url = Yii::app()->createUrl('psi/TrackingUpdate', array('trackingIndex' => $tid));
        } else {
            $url = Yii::app()->createUrl('psi/update', array('id' => $pid));
        }
        header("Content-Type:text/html;charset=utf-8");
        echo '<script>alert("' . $msg . '");window.location.href="' . $url . '";</script>';
    }

    //从PricingDetail记录关联Tracking记录
    public function actionAddMid($pricingIndex) {
        header("Content-Type:text/html;charset=utf-8");
        $this->layout = 'pop';
        $pricing = Pricing::model()->findByPk((int) $pricingIndex);

        if ($_REQUEST['midIndex']) {
            $model = MidTab::model()->findByPk((int) $_REQUEST['midIndex']);
        }

        if (!$model) {
            $model = new MidTab;
        }

        if ($model->tracking->ShippingStatus == 'Delivery') {
            echo '<script>alert("不允许编辑");parent.$.fancybox.close();</script>';
            exit;
        }

        $model->PricingIndex = $pricingIndex;

        if (isset($_POST['MidTab'])) {
            $model->attributes = $_POST['MidTab'];
            //判断一下如果是添加，如果这个group中已经有这个产品了，就更新下，不允许重复关联
            if ($model->isNewRecord) {
                if ($model->TrackingIndex) {
                    $condition = new CDbCriteria();
                    $condition->addCondition('PricingIndex=' . $pricingIndex);
                    $condition->addCondition('TrackingIndex=' . $model->TrackingIndex);
                    $have = MidTab::model()->find($condition);
                    unset($condition);

                    if ($have) {
                        echo '<script>alert("记录已存在");parent.$.fancybox.close();</script>';
                        exit;
                    }
                }
            }

            $model->ProductID = $pricing->ProductID;

            if ($model->save()) {
                echo '<script>alert("更新成功");parent.$.fancybox.close();</script>';
            } else {
                echo '<script>alert("更新失败，请检查数量");</script>';
            }
        }

        $condition = new CDbCriteria();
        $condition->with = 'mids';
        $condition->addCondition('mids.PricingIndex=' . $pricing->PricingIndex);
        $nows = Tracking::model()->findAll($condition);
        unset($condition);

        $condition = new CDbCriteria();
        $condition->addCondition("ShippingStatus='DataLogging'");
        if ($nows) {
            $condition->addNotInCondition('TrackingIndex', CHtml::listData($nows, 'TrackingIndex', 'TrackingIndex'));
        }
        $trackings = Tracking::model()->findAll($condition);
        unset($condition);

        $trackArr = array();
        if ($model->tracking) {
            $trackArr[] = array(
                'key' => $model->tracking->TrackingIndex,
                'show' => '[' . $model->tracking->TrackingIndex . ']' . '[' . $model->tracking->CarrierNo . ']' . '[' . $model->tracking->EBoxNumber . ']'
            );
        }

        if ($trackings) {
            foreach ($trackings as $tracking) {
                $tempArr = array();
                $tempArr['key'] = $tracking->TrackingIndex;
                $tempArr['show'] = '[' . $tracking->TrackingIndex . ']' . '[' . $tracking->CarrierNo . ']' . '[' . $tracking->EBoxNumber . ']';
                $trackArr[] = $tempArr;
            }
        }

        if ($model->ToLAQty <= 0) {
            $model->ToLAQty = 1;
        }

        $this->render('addMid', array(
            'model' => $model,
            'trackings' => $trackArr,
        ));
    }

    //导出Tracking
    public function actionExportTracking() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.TrackingIndex desc';
        $criteria->with = 'mids';

        $search['ShippingStatus'] = $_REQUEST['ShippingStatus'];
        $search['CarrierNo'] = $_REQUEST['CarrierNo'];
        $search['EBoxNumber'] = $_REQUEST['EBoxNumber'];
        $search['ToLAMethod'] = $_REQUEST['ToLAMethod'];
        $search['ShipDate'] = $_REQUEST['ShipDate'];
        $search['ArriveDate'] = $_REQUEST['ArriveDate'];
        $search['ShippingType'] = $_REQUEST['ShippingType'];

        if ($search['ShippingStatus']) {
            $criteria->addCondition("t.ShippingStatus='" . $search['ShippingStatus'] . "'");
        }
        if ($search['CarrierNo']) {
            $criteria->addCondition("t.CarrierNo like '%" . $search['CarrierNo'] . "%'");
        }
        if ($search['EBoxNumber']) {
            $criteria->addCondition("t.EBoxNumber like '%" . $search['EBoxNumber'] . "%'");
        }
        if ($search['ToLAMethod']) {
            $criteria->addCondition("t.ToLAMethod = '" . $search['ToLAMethod'] . "'");
        }
        if ($search['ShipDate']) {
            $criteria->addCondition("t.ShipDate='" . $search['ShipDate'] . "'");
        }
        if ($search['ArriveDate']) {
            $criteria->addCondition("t.ArriveDate='" . $search['ArriveDate'] . "'");
        }
        if ($search['ShippingType']) {
            $criteria->addCondition("t.ShippingType='" . $search['ShippingType'] . "'");
        }

        $rowTable = Tracking::model()->findAll($criteria);
        $trackings = array();
        foreach ($rowTable as $row) {
            if($row->mids){
                foreach($row->mids as $mid){
                    $tracking = array();
                    if($row->ShipDate){
                        $tracking['A'] = date('Y-m-d',  strtotime($row->ShipDate));
                    }                    
                    $tracking['B'] = $row->CarrierNo;
                    $tracking['C'] = $mid->product->ProductName;
                    $tracking['D'] = $mid->product->ProductDetail;
                    $tracking['E'] = $mid->product->ProductModel;
                    $tracking['F'] = $mid->ToLAQty;
                    if($row->ShippingType=='Container'){
                        $tracking['G'] = $mid->CBoxNumber;
                    }else{
                        $tracking['G'] = $row->EBoxNumber;
                    }                    
                    $tracking['H'] = $row->Comment;
                    $tracking['I'] = $row->OETrackingStatus;
                    
                    $trackings[]=$tracking;
                }
            }else{
                $tracking = array();
                if ($row->ShipDate) {
                    $tracking['A'] = date('Y-m-d', strtotime($row->ShipDate));
                }
                $tracking['B'] = $row->CarrierNo;
                $tracking['G'] = $row->EBoxNumber;
                $tracking['H'] = $row->Comment;
                $tracking['I'] = $row->OETrackingStatus;

                $trackings[] = $tracking;
            }        
        }

        spl_autoload_unregister(array('YiiBase', 'autoload'));
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel.php');
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel/IOFactory.php');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '寄出日期')
                ->setCellValue('B1', '货柜编号（快递单号）')
                ->setCellValue('C1', '产品名称')
                ->setCellValue('D1', '产品细节')
                ->setCellValue('E1', '产品编号')
                ->setCellValue('F1', '寄出数量')
                ->setCellValue('G1', '箱号')
                ->setCellValue('H1', '运单资料')
                ->setCellValue('I1', '状态跟踪');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);

        $i = 2;
        foreach ($trackings as $item) {
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $i, $item['A'])
                    ->setCellValueExplicit('B'.$i, $item['B'], PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('C' . $i, $item['C'])
                    ->setCellValue('D' . $i, $item['D'])
                    ->setCellValue('E' . $i, $item['E'])
                    ->setCellValue('F' . $i, $item['F'])
                    ->setCellValue('G' . $i, $item['G'])
                    ->setCellValue('H' . $i, $item['H'])
                    ->setCellValue('I' . $i, $item['I']);
            $i++;
        }

        $filename = 'Tracking.xls';
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename=' . urlencode($filename) . '');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        spl_autoload_register(array('YiiBase', 'autoload'));
    }

}
